<template>
  <div class="page-container">
    <ApplicationCashoutSearch
      :query="state.query"
      @reset="reset"
      @getList="getList"
    ></ApplicationCashoutSearch>
    <div
      class="in-container"
      style="margin-top: 8px; height: calc(100% - 180px)"
    >
      <div class="btn-box">
        <el-button type="default" icon="RefreshRight" @click="getList">
        </el-button>
        <el-button type="primary" @click="qkClick"> 请款单核销 </el-button>
        <!-- <el-button type="primary" @click="deleWriteOff"> 删除 </el-button> -->
        <el-dropdown
          ref="dropdown1"
          trigger="hover"
          style="margin-left: 10px; margin-right: 10px"
          @command="aduitCommand"
        >
          <el-button type="primary"> 审核管理 </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item :command="1">
                <div style="min-width: 50px">提交</div>
              </el-dropdown-item>
              <el-dropdown-item :command="2">通过</el-dropdown-item>
              <el-dropdown-item :command="-1">驳回</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <!-- <el-button type="primary" @click="downloadFile"> 导出EXCEL </el-button> -->
      </div>
      <AppPageTable
        stripe
        :data="state.tableData.data"
        @change="getList"
        :autostyle="'height: calc(100% - 50px);'"
        :option="state.tableData.option"
        v-loading="state.tableLoading"
      >
        <el-table-column type="selection" width="40" align="center" />
        <el-table-column
          prop="doccode"
          width="130"
          label="付款单号"
          align="center"
          showOverflowTooltip
        >
          <template #default="scope">
            <span class="doccode-text" @click="toEditPage(scope.row)">{{
              scope.row.doccode
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="审核状态"
          width="100"
          showOverflowTooltip
          align="center"
        >
          <template #default="scope">
            {{
              scope.row.checkStatus == 0
                ? '草拟'
                : scope.row.checkStatus == 1
                ? '提交审核'
                : scope.row.checkStatus == 2
                ? '审核通过'
                : scope.row.checkStatus == -1
                ? '驳回'
                : ''
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="checkTime"
          width="100"
          align="center"
          showOverflowTooltip
          label="审核日期"
        >
          <template #default="scope">
            {{
              scope.row.checkTime
                ? $utils.formatDateTime(scope.row.checkTime, 'YYYY-MM-DD')
                : ''
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="checkBy"
          width="100"
          label="审核人"
          showOverflowTooltip
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="salesName"
          label="业务员"
          width="100"
          align="center"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          label="付款日期"
          width="100"
          align="center"
          showOverflowTooltip
        >
          <template #default="scope">
            {{
              scope.row.docdate
                ? $utils.formatDateTime(scope.row.docdate, 'YYYY-MM-DD')
                : ''
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="entCode"
          label="单位编号"
          width="100"
          align="center"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          prop="entName"
          label="单位名称"
          width="100"
          align="center"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          label="类型"
          align="center"
          width="100"
          showOverflowTooltip
        >
          <template #default="scope">
            {{ scope.row.doctype == 1 ? '收款' : '付款' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="currency"
          label="币种"
          align="center"
          showOverflowTooltip
          width="100"
        >
        </el-table-column>
        <el-table-column
          prop="canverificationMoney"
          label="销账金额"
          align="center"
          width="100"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          prop="sumverificationMoney"
          label="已销金额"
          align="center"
          width="100"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          prop="xunVerificationMoney"
          label="未销金额"
          align="center"
          width="100"
          showOverflowTooltip
        >
          <!-- <template #default="scope">
                        {{ scope.row.getSumVerificationMoney ? scope.row.getSumVerificationMoney : "" }}
                    </template> -->
        </el-table-column>
        <el-table-column
          prop="bankAccount"
          label="账户"
          align="center"
          width="100"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          prop="bankAccountName"
          label="账号"
          align="center"
          width="100"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          prop="memo"
          align="center"
          label="备注"
          showOverflowTooltip
        >
        </el-table-column>
      </AppPageTable>
    </div>

    <!-- 修改 -->
    <el-dialog
      v-model="state.show"
      title="请款单"
      width="1000px"
      modal-class="application-cash-dailog"
      @close="invoiceClose"
    >
      <!-- <el-form label-suffix="：" label-width="100px" size="small">
        <el-form-item label="请款单号">
          <el-select
            v-model="state.modfiyForm.DocNo"
            placeholder="请选择"
            style="width: 100%"
            clearable
            filterable
            remote
            :remote-method="getApplicaList"
          >
            <el-option
              v-for="item in state.applicaList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form> -->
      <el-form
        :inline="true"
        label-suffix="："
        :label-width="'80px'"
        :size="'small'"
        ref="form"
      >
        <el-row>
          <el-col :span="10">
            <el-form-item label="请款单号" style="width: 100%">
              <el-input
                v-model="state.queryReq.DocNo"
                clearable
                placeholder="请输入"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <div class="flex-container" style="margin-left: 8px">
              <el-button
                type="primary"
                icon="search"
                @click="getAppcationListTable"
                size="small"
              >
                搜索
              </el-button>
              <el-button
                type="info"
                icon="refresh"
                @click="resetReq"
                size="small"
              >
                重置
              </el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <AppPageTable
        stripe
        :data="state.tableDataReq.data"
        @change="getAppcationListTable"
        :height="400"
        :option="state.tableDataReq.option"
        v-loading="state.tableLoadingReq"
      >
        <el-table-column type="selection" width="40" align="center" />
        <el-table-column
          prop="doccode"
          label="请款单号"
          align="center"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column label="请款日期" align="center" showOverflowTooltip>
          <template #default="scope">
            {{
              scope.row.docdate
                ? $utils.formatDateTime(scope.row.docdate, 'YYYY-MM-DD')
                : ''
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="entCode"
          label="单位编号"
          align="center"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          prop="entFullname"
          label="单位名称"
          align="center"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          prop="currency"
          label="币种"
          align="center"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          prop="totalmoney"
          label="金额"
          align="center"
          showOverflowTooltip
        >
        </el-table-column>
      </AppPageTable>

      <template #footer>
        <div class="button-container">
          <el-button type="default" @click="state.show = false">取消</el-button>
          <el-button type="primary" @click="modifySubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import CashSearchFrom from './components/CashSearchFrom.vue'
import ApplicationCashoutSearch from './components/ApplicationCashoutSearch.vue'
import AppPageTable, { useTableOption } from '@/components/AppPageTable2'
import request from '@/public/request'
import dayjs from 'dayjs'
import { ElMessageBox, ElMessage } from 'element-plus'
import { fileDownload } from '@/public/publicUtils'
import { useRoute, useRouter } from 'vue-router'
import AppSearchForm from '@/components/AppSearchForm.vue'

const Route = useRoute()
const Router = useRouter()

const state = reactive({
  // 查询条件
  query: {
    DocCode: '', //收付款单号
    // InvoiceNo: '', //发票号
    // BlNo: '', //提单号
    SalesId: '', //业务员
    SmallAmount: '', //起始金额
    BigAmout: '', //截止金额
    EntFullName: '', //结算对象
    FeeStatus: 0, //核销状态
    // FinaceCode: '', //对账单号
    CheckStatus: -2, //审核状态
    Currency: '', //币种
    // Memo: '', //备注
    // PayStartTime: '', //收付款日期
    // PayEndTime: '', //
    DocDateList: null,
    DocType: 0 //类型 0 付款 1 收款
  },
  queryReq: {
    DocNo: '' //请款单号
  },
  //表格数据
  tableData: {
    data: [],
    option: useTableOption()
  },
  // 请款选择
  tableDataReq: {
    data: [],
    option: useTableOption()
  },
  tableLoading: false,
  tableLoadingReq: false,
  show: false,
  modfiyForm: {
    id: ''
  },
  applicaList: [],
  applicaLoading: false
})
// 获取请款单列表
const getApplicaList = async (val) => {
  state.applicaLoading = true
  let res = await request.get('/api/docreqcash/queryDialogPage', {
    DocNo: val,
    PageIndex: 1,
    PageSize: 999
  })
  res.content.forEach((item) => {
    item.label = item.doccode
    item.value = item.id
  })
  state.applicaList = res.content
  state.applicaLoading = false
}

// 清空查询:请款列表
function resetReq() {
  state.queryReq = {
    DocNo: '' //请款单号
  }
  getAppcationListTable()
}

//获取请款单列表
const getAppcationListTable = async () => {
  let search = {
    PageIndex: state.tableDataReq.option.page,
    PageSize: state.tableDataReq.option.pageSize,
    DocNo: state.queryReq.DocNo
  }
  state.tableLoadingReq = true
  let res = await request.get('/api/docreqcash/queryDialogPage', search)
  state.tableDataReq.data = res.content
  state.tableDataReq.option.total = res.totalElements
  state.tableLoadingReq = false
}

// 销账点击
const qkClick = () => {
  state.show = true
  state.queryReq = {
    DocNo: '' //请款单号
  }
  state.tableDataReq.option.page = 1
  getAppcationListTable()
}
const modifySubmit = () => {
  // let id = state.modfiyForm.DocNo
  // state.modfiyForm.DocNo = ''
  if (state.tableDataReq.option.selected.length != 1) {
    ElMessage.warning('请选择一条数据')
    return
  }
  let id = state.tableDataReq.option.selected[0].id
  // return
  state.show = false
  Router.push('/finance/ApplicaCashDetail?qkid=' + id)
}

// 获取列表数据
const getList = async () => {
  let query = JSON.parse(JSON.stringify(state.query))
  if (state.query.CheckStatus < 0) {
    query.CheckStatus = ''
  }
  if (state.query.FeeStatus < 0) {
    query.FeeStatus = ''
  }
  let search = {
    PageIndex: state.tableData.option.page,
    PageSize: state.tableData.option.pageSize,
    ...query
  }
  state.tableLoading = true
  let res = await request.post('/api/doccash/querycashList', search)
  if (query.CheckStatus === '') {
    state.query.CheckStatus = -2
  }
  if (query.FeeStatus === '') {
    state.query.FeeStatus = -2
  }
  res.content.forEach((item) => {
    item.xunVerificationMoney = Math.trunc(
      item.canverificationMoney - item.sumverificationMoney
    )
  })
  state.tableData.data = res.content
  state.tableData.option.total = res.totalElements
  state.tableLoading = false
}
// 重置
const reset = () => {
  state.query = {
    DocCode: '', //收付款单号
    // InvoiceNo: '', //发票号
    // BlNo: '', //提单号
    SalesId: '', //业务员
    SmallAmount: '', //起始金额
    BigAmout: '', //截止金额
    EntFullName: '', //结算对象
    FeeStatus: 0, //核销状态
    // FinaceCode: '', //对账单号
    CheckStatus: -2, //审核状态
    Currency: '', //币种
    // Memo: '', //备注
    // PayStartTime: '', //收付款日期
    // PayEndTime: '', //
    DocDateList: null,
    DocType: 0 //类型 0 付款 1 收款
  }
  getList()
}
// 删除销账
const deleWriteOff = async () => {
  if (!state.tableData.option.selected.length) {
    ElMessage.warning('请选择数据')
    return
  }
  let idArray = []
  let flag = true
  for (const iterator of state.tableData.option.selected) {
    if (iterator.sumverificationMoney && iterator.sumverificationMoney != 0) {
      flag = false
      ElMessage.error('已核销数据不能删除')
      break
    }
    idArray.push(iterator.id)
  }
  if (!flag) {
    return
  }
  ElMessageBox.confirm('是否确定执行删除操作？?', '消息提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    let res = await request.post('/api/doccash/delete', {
      idArray
    })
    if (res.status) {
      getList()
      ElMessage.success('成功')
    } else {
      ElMessage.warning(res.message)
    }
  })
}
// 下拉框审核点击
const aduitCommand = async (val) => {
  if (!state.tableData.option.selected.length) {
    ElMessage.warning('请选择数据')
    return
  }
  let req = {
    ids: [],
    checkStatus: val
  }
  let flagOfSubmit = true
  for (const iterator of state.tableData.option.selected) {
    if (val == 1) {
      if (iterator.checkStatus > 0) {
        flagOfSubmit = false
        ElMessage.error('只能提交草稿或者驳回状态的数据')
        break
      }
      if (!iterator.entId) {
        flagOfSubmit = false
        ElMessage.error(`单号为${iterator.doccode}的结算对象为空,不能提交`)
        break
      }
      if (!iterator.currency) {
        flagOfSubmit = false
        ElMessage.error(`单号为${iterator.doccode}的实收币种为空,不能提交`)
        break
      }
      if (!iterator.sumtotalmoney || iterator.sumtotalmoney == 0) {
        flagOfSubmit = false
        ElMessage.error(`单号为${iterator.doccode}的实收金额为空,不能提交`)
        break
      }
      if (!iterator.docdate) {
        flagOfSubmit = false
        ElMessage.error(`单号为${iterator.doccode}的收款日期为空,不能提交`)
        break
      }
      if (!iterator.feeCurrency) {
        flagOfSubmit = false
        ElMessage.error(`单号为${iterator.doccode}的销帐币种为空,不能提交`)
        break
      }
      if (!iterator.exchangeRate || iterator.exchangeRate == 0) {
        flagOfSubmit = false
        ElMessage.error(`单号为${iterator.doccode}的汇率为空,不能提交`)
        break
      }
      if (
        !iterator.sumverificationMoney ||
        iterator.sumverificationMoney == 0
      ) {
        flagOfSubmit = false
        ElMessage.error(`单号为${iterator.doccode}的销帐金额为空,不能提交`)
        break
      }
      if (!iterator.bankAccount) {
        flagOfSubmit = false
        ElMessage.error(`单号为${iterator.doccode}的银行账号为空,不能提交`)
        break
      }
    } else if (val == 2) {
      if (iterator.checkStatus != 1) {
        flagOfSubmit = false
        ElMessage.error('只能审核提交状态的数据')
        break
      }
    } else if (val == -1) {
      if (iterator.checkStatus < 1) {
        flagOfSubmit = false
        ElMessage.error('只能驳回通过、提交的数据')
        break
      }
    }
    req.ids.push(iterator.id)
  }
  if (!flagOfSubmit) {
    return
  }
  let res = await request.post('/api/doccash/checkTable', req)
  if (res.status) {
    getList()
    ElMessage.success('成功')
  } else {
    ElMessage.warning(res.message)
  }
}

// 跳转收款编辑页面
const toEditPage = (row) => {
  Router.openTab({
    path: '/finance/ApplicaCashDetail',
    query: {
      id: row.id,
      title: '付款详情' + row.doccode,
      iscash: true
    }
  })
}

// 导出excel
const downloadFile = async () => {
  let feeParams = []
  let query = JSON.parse(JSON.stringify(state.query))
  if (query.CheckStatus < 0) {
    query.CheckStatus = ''
  }
  if (query.FeeStatus < 0) {
    query.FeeStatus = ''
  }
  query.DocDateList = [
    query.PayStartTime ? query.PayStartTime : '',
    query.PayEndTime ? query.PayEndTime : ''
  ]
  delete query.PayStartTime
  delete query.PayEndTime
  fileDownload('/api/doccash/download', query, '付款销账')
    .then(() => {})
    .catch((err) => {
      ElMessage.warning('文件导出失败')
    })
}
</script>

<style lang="scss" scoped>
.btn-box {
  margin-bottom: 8px;
}

.doccode-text {
  color: rgb(24, 144, 255);
  // white-space: nowrap;
  // overflow: hidden;
  // text-overflow: ellipsis;
  cursor: pointer;
}

:deep(.application-cash-dailog) {
  .el-dialog__header {
    border-bottom: 1px solid #e8e8e8;
  }

  .el-dialog__body {
    padding-top: 16px;
  }

  .el-dialog__footer {
    border-top: 1px solid #e8e8e8;

    div {
      display: flex;
      justify-content: flex-end;
      align-items: center;
    }
  }
}
</style>
